//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.service;

import com.kun.framework.web.web.vo.ValueLabelVo;
import com.kun.portal.webframe.dao.FwTeamDao;
import com.kun.portal.webframe.dao.FwTeamModuleDao;
import com.kun.portal.webframe.dao.FwUserDao;
import com.kun.portal.webframe.po.FwRolePo;
import com.kun.portal.webframe.po.FwTeamModulePo;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FwTeamService {
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private FwUserDao fwUserDao;
    @Autowired
    private FwTeamDao fwTeamDao;
    @Autowired
    private FwTeamModuleDao moduleDao;

    public FwTeamService() {
    }

    public Page<FwTeamPo> queryAll(Pageable pageable) {
        return this.fwTeamDao.findAll(pageable);
    }

    public List<FwTeamPo> queryAll(boolean all) {
//        Specification <FwTeamPo> query =  new Specification<FwTeamPo>() {
//            @Override
//            public Predicate toPredicate(Root<FwTeamPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//
//                return cb.notEqual(root.get("teamStatus"),"0");
//            }
//        };
//        if(!all){
//            return this.fwTeamDao.findAll();
      //  }
        String sql = "select distinct t from FwTeamPo t left  join fetch t.userList left join fetch t.roleSet left join fetch t.dutyUser  ";
        if(!all){
           sql += " where  t.teamStatus = 1";
        }
        sql+= " order by t.teamName desc";
       Query query= entityManager.createQuery(sql);
        List<FwTeamPo> list = query.getResultList();

        //List<FwTeamPo> list = this.fwTeamDao.findAll(query);
        return list;
    }

    public FwTeamPo findByTeamId(String teamId) {
        return this.fwTeamDao.findByTeamId(teamId);
    }

    public List<FwTeamPo> findTeamAndChildren(String teamId) {
        return this.fwTeamDao.findTeamAndChildren(teamId);
    }

    public Page<FwTeamPo> findByCreatorAndTeamNameContaining(String userId, String teamName, Pageable pageable) {
        return this.fwTeamDao.findByCreatorAndTeamNameContainingOrderByTeamCode(userId, teamName, pageable);
    }

    public FwTeamPo addFwTeam(FwTeamPo fwteam) {
        FwTeamPo fwteamPo = (FwTeamPo)this.fwTeamDao.save(fwteam);
        String teamId = fwteamPo.getTeamId();
        List<String> moduleList = fwteam.getModuleList();
        this.saveTeamModule(teamId, moduleList);
        return fwteamPo;
    }

    @Transactional
    public FwTeamPo updateFwTeam(FwTeamPo fwteam) {
        FwTeamPo fwteamPo = (FwTeamPo)this.fwTeamDao.save(fwteam);
        String teamId = fwteam.getTeamId();
        List<String> moduleList = fwteam.getModuleList();
        this.saveTeamModule(teamId, moduleList);
        return fwteamPo;
    }

    public void saveTeamModule(String teamId, List<String> moduleList) {
        if(moduleList != null) {
            this.moduleDao.deleteByTeamId(teamId);
            List<FwTeamModulePo> teamModuleList = new ArrayList();
            Iterator var5 = moduleList.iterator();

            while(var5.hasNext()) {
                String moduleId = (String)var5.next();
                teamModuleList.add(new FwTeamModulePo(teamId, moduleId));
            }

            this.moduleDao.save(teamModuleList);
        }

    }

    @Transactional
    public void deleteFwTeam(String teamId) {
        this.fwTeamDao.delete(teamId);
    }

    public List<ValueLabelVo> findFwTeamByCreator(String creator) {
        Query query = this.entityManager.createNativeQuery("select r.team_id as value, r.team_code as code, r.team_name as label from fw_team r where r.team_status!='0' AND r.creator=?1", ValueLabelVo.class);
        query.setParameter(1, creator);
        return query.getResultList();
    }

    public List<String> findFwTeamByUserId(String userId) {
        Query query = this.entityManager.createNativeQuery("select r.team_id from fw_team_user r where r.user_id=?1");
        query.setParameter(1, userId);
        return query.getResultList();
    }

    public List<String> findFwTeamByRoleId(String roleId) {
        Query query = this.entityManager.createNativeQuery("select r.team_id from fw_team_role r where r.role_id=?1");
        query.setParameter(1, roleId);
        return query.getResultList();
    }

    @Transactional
    public void updateFwTeamUserByUserId(List<String> teamIds, String userId) {
        FwUserPo user = (FwUserPo)this.fwUserDao.findOne(userId);
        Set<FwTeamPo> teams = new HashSet();
        Iterator var6 = teamIds.iterator();

        while(var6.hasNext()) {
            String teamId = (String)var6.next();
            FwTeamPo team = new FwTeamPo();
            team.setTeamId(teamId);
            teams.add(team);
        }

        //user.setTeams(teams);
        this.fwUserDao.save(user);
    }

    @Transactional
    public void updateFwRoleTeamByTeamId(List<String> roleIds, String teamId) {
        FwTeamPo team = (FwTeamPo)this.fwTeamDao.findOne(teamId);
        Set<FwRolePo> roleSet = new HashSet();
        Iterator var6 = roleIds.iterator();

        while(var6.hasNext()) {
            String roleId = (String)var6.next();
            FwRolePo role = new FwRolePo();
            role.setRoleId(roleId);
            roleSet.add(role);
        }

        team.setRoleSet(roleSet);
        this.fwTeamDao.save(team);
    }

    @Transactional
    public List<FwUserPo> findUsersByTeamId(String teamId) {
        FwTeamPo resultTeam = (FwTeamPo)this.fwTeamDao.findOne(teamId);
        Hibernate.initialize(resultTeam.getUserList());
        return new ArrayList<>(resultTeam.getUserList()) ;
    }

    @Transactional
    public void updateFwTeamUserByTeamId(String teamId, List<FwUserPo> userList) {
        FwTeamPo teamPo = (FwTeamPo)this.fwTeamDao.findOne(teamId);
        if(userList!=null){
            String s="";
            boolean first=true;

            for(FwUserPo userPo :userList){
                if(first){
                    s+="'"+userPo.getUserId()+"'";
                    first=false;
                }else{
                    s+=",'"+userPo.getUserId()+"'";
                }

            }
            List<FwUserPo> list= entityManager.createQuery("select u from FwUserPo u where u.userId in ("+s+") ").getResultList();
            teamPo.setUserList(new HashSet<>(list));
        }else{
            teamPo.setUserList(null);
        }

        this.fwTeamDao.save(teamPo);
    }

    public List<Map<String, String>> findDetailList(String teamId) {
        Query query = this.entityManager.createNativeQuery("select team_id teamId, team_name teamName, team_code teamCode, team_level teamLevel, team_status teamStatus, parent_code parentCode,area_code areaCode from fw_team where team_id like ?1 order by team_id,team_level");
        query.setParameter(1, teamId + "%");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, String>> resultList = query.getResultList();
        Map<String, Map<String, String>> idMap = new HashMap();
        this.transToIdMap(resultList, idMap, "teamId");
        this.countTeam(idMap, "userNum", "SELECT a.team_id id, COUNT(b.user_id) num FROM fw_team a LEFT JOIN fw_team_user b ON a.team_id = b.team_id WHERE a.team_id LIKE '" + teamId + "%' GROUP BY a.team_id");
        this.countTeam(idMap, "tabNum", "SELECT a.team_id id, COUNT(b.tab_id) num FROM fw_team a LEFT JOIN dp_dev_physic_tab b ON a.team_id = b.team_id WHERE a.team_id LIKE '" + teamId + "%' GROUP BY a.team_id");
        this.countTeam(idMap, "procNum", "SELECT a.team_id id, COUNT(b.xml_id) num FROM fw_team a LEFT JOIN dp_dev_proc b ON a.team_id = b.team_code WHERE a.team_id LIKE '" + teamId + "%' GROUP BY a.team_id");
        this.countTeam(idMap, "resNum", "SELECT a.team_id id, COUNT(b.res_team_id) num FROM fw_team a LEFT JOIN dp_dev_team_res b ON a.team_id = b.team_id WHERE a.team_id LIKE '" + teamId + "%' GROUP BY a.team_id");
        this.countTeam(idMap, "moduleNum", "SELECT a.team_id id, COUNT(b.module_id) num FROM fw_team a LEFT JOIN fw_team_module b ON a.team_id = b.team_id WHERE a.team_id LIKE '" + teamId + "%' GROUP BY a.team_id");
        this.transToList(resultList, idMap);
        return resultList;
    }

    public List<Map<String, String>> findAllDetailList() {
        Query query = this.entityManager.createNativeQuery("select team_id teamId, team_name teamName, team_code teamCode, team_level teamLevel, team_status teamStatus, parent_code parentCode from fw_team order by team_id");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, String>> resultList = query.getResultList();
        Map<String, Map<String, String>> idMap = new HashMap();
        this.transToIdMap(resultList, idMap, "teamId");
        this.countTeam(idMap, "userNum", "SELECT a.team_id id, COUNT(b.user_id) num FROM fw_team a LEFT JOIN fw_team_user b ON a.team_id = b.team_id GROUP BY a.team_id");
        this.countTeam(idMap, "tabNum", "SELECT a.team_id id, COUNT(b.tab_id) num FROM fw_team a LEFT JOIN dp_dev_physic_tab b ON a.team_id = b.team_id GROUP BY a.team_id");
        this.countTeam(idMap, "procNum", "SELECT a.team_id id, COUNT(b.xml_id) num FROM fw_team a LEFT JOIN dp_dev_proc b ON a.team_id = b.team_code GROUP BY a.team_id");
        this.countTeam(idMap, "resNum", "SELECT a.team_id id, COUNT(b.res_team_id) num FROM fw_team a LEFT JOIN dp_dev_team_res b ON a.team_id = b.team_id GROUP BY a.team_id");
        this.countTeam(idMap, "moduleNum", "SELECT a.team_id id, COUNT(b.module_id) num FROM fw_team a LEFT JOIN fw_team_module b ON a.team_id = b.team_id GROUP BY a.team_id");
        this.transToList(resultList, idMap);
        return resultList;
    }

    private void transToList(List<Map<String, String>> resultList, Map<String, Map<String, String>> idMap) {
        resultList.clear();
        Iterator it = idMap.entrySet().iterator();

        while(it.hasNext()) {
            Entry entry = (Entry)it.next();
            resultList.add((Map)entry.getValue());
        }

    }

    private void transToIdMap(List<Map<String, String>> resultList, Map<String, Map<String, String>> idMap, String idName) {
        Iterator var5 = resultList.iterator();

        while(var5.hasNext()) {
            Map<String, String> map = (Map)var5.next();
            idMap.put((String)map.get(idName), map);
        }

    }

    public void countTeam(Map<String, Map<String, String>> summaryMap, String countName, String sql) {
        Query query = this.entityManager.createNativeQuery(sql);
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, String>> list = query.getResultList();
        Iterator var7 = list.iterator();

        while(var7.hasNext()) {
            Map map = (Map)var7.next();
            Map<String, String> idMap = (Map)summaryMap.get(map.get("id"));
            BigInteger num = (BigInteger)map.get("num");
            idMap.put(countName, num.toString());
            summaryMap.put((String)map.get("id"), idMap);
        }

    }

    public List<FwTeamPo> findByTeamCode(String teamCode) {
        return this.fwTeamDao.findByTeamCode(teamCode);
    }

    public List<Map<String, String>> findTopTeamSelect() {
        Query query = this.entityManager.createNativeQuery("select team_name label, team_id value from fw_team where team_status!='0' AND parent_code IS NULL or parent_code=''");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<Map<String, String>> findSelectByParentCode(String parentCode) {
        Query query = this.entityManager.createNativeQuery("select team_name label, team_id value from fw_team where team_status!='0' AND parent_code like ?1");
        query.setParameter(1, parentCode + "%");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<FwTeamPo> findByFwTeamUnique(final Map<String, String> map) {
        return this.fwTeamDao.findAll(new Specification<FwTeamPo>() {
            public Predicate toPredicate(Root<FwTeamPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicate = new ArrayList();
                Iterator var6 = map.keySet().iterator();

                while(var6.hasNext()) {
                    String key = (String)var6.next();
                    if(FwTeamService.UniqueKey.valueOf(key) != null) {
                        String value = (String)map.get(key);
                        if(StringUtils.isNotBlank(value)) {
                            predicate.add(cb.equal(root.get(key).as(String.class), value));
                        }
                    }
                }

                Predicate[] p = new Predicate[predicate.size()];
                query.where(cb.and((Predicate[])predicate.toArray(p)));
                return query.getRestriction();
            }
        });
    }

    @Transactional
    public void deleteFwTeamUserByUserId(String userId) {
        this.fwTeamDao.deleteFwTeamUserByUserId(userId);
    }

    @Transactional
    public void deleteTeamUsers(String teamId, String userId) {
        this.fwTeamDao.deleteFwTeamUserByUserIdAndTeamId(userId, teamId);
    }

    public List findTeamRole(String teamId, String teamLevel) {
        String sql = " SELECT a.role_id roleId,a.role_code roleCode,a.role_name roleName,        (CASE WHEN a.team_id = '' OR a.team_id IS NULL THEN '公有角色' ELSE '私有角色' END ) roleType   FROM fw_role a WHERE a.team_id =?1";
        if("1".equals(teamLevel)) {
            sql = sql + " OR a.team_id = '' OR a.team_id IS NULL";
        }

        Query query = this.entityManager.createNativeQuery(sql);
        query.setParameter(1, teamId);
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List findTeamUserRole(String teamId, String key) {
        String sql = "SELECT  k.*,d.role_id roleId,d.role_code roleCode,d.role_name roleName,      (CASE WHEN d.team_id = '' OR d.team_id IS NULL THEN '公有角色' ELSE '私有角色' END) roleType FROM (SELECT DISTINCT b.user_id userId,b.user_name userCode,b.user_cn_name userName, b.phone,b.email         FROM fw_team_user a,fw_user b        WHERE a.user_id = b.user_id           AND a.team_id = ?1          AND b.user_status = '1'";
        if(key != null && !"".equals(key)) {
            sql = sql + "   AND (b.user_name like ?2 or b.user_cn_name like ?2) ";
        }

        sql = sql + ") k LEFT JOIN fw_role_user c ON k.userId = c.user_id  AND c.role_id IN (SELECT role_id FROM fw_role WHERE team_id = '' OR team_id IS NULL OR team_id =?1) LEFT JOIN fw_role d ON c.role_id = d.role_id";
        Query query = this.entityManager.createNativeQuery(sql);
        query.setParameter(1, teamId);
        if(key != null && !"".equals(key)) {
            String qkey = "%" + key + "%";
            query.setParameter(2, qkey);
        }

        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List getTeamTree(String teamId) {
        List<Map<String, Object>> result = new ArrayList();
        List<FwTeamPo> allList = this.getAllTeams();
        Iterator var7 = allList.iterator();

        while(var7.hasNext()) {
            FwTeamPo obj = (FwTeamPo)var7.next();
            if(obj.getTeamId().equals(teamId)) {
                String tId = obj.getTeamId();
                String tName = obj.getTeamName();
                Map<String, Object> map = new HashMap();
                map.put("value", tId);
                map.put("label", tName);
                map.put("fullValue", tId);
                map.put("fullLabel", tName);
                map.put("children", this.getChildMap(allList, tId, tId, tName));
                result.add(map);
            }
        }

        return result;
    }

    public List<FwTeamPo> getAllTeams() {
        return this.fwTeamDao.findAll();
    }

    private List<Map<String, Object>> getChildMap(List<FwTeamPo> list, String pid, String fullValue, String fullText) {
        List<Map<String, Object>> childList = new ArrayList();
        Iterator var9 = list.iterator();

        while(var9.hasNext()) {
            FwTeamPo obj = (FwTeamPo)var9.next();
            if(!StringUtils.isBlank(obj.getParentCode()) && pid.equals(obj.getParentCode())) {
                Map<String, Object> map = new HashMap();
                String tId = obj.getTeamId();
                String tName = obj.getTeamName();
                map.put("value", tId);
                map.put("label", tName);
                map.put("fullValue", fullValue + ">" + tId);
                map.put("fullLabel", fullText + ">" + tName);
                map.put("children", this.getChildMap(list, tId, fullValue + ">" + tId, fullText + ">" + tName));
                childList.add(map);
            }
        }

        if(childList.size() == 0) {
            return null;
        } else {
            return childList;
        }
    }

    private static enum UniqueKey {
        teamId,
        teamCode,
        teamName;

        private UniqueKey() {
        }
    }
}
